/**
 * @author Sebastian
 * @version 2.0
 * @date 2024/6/4 21:24
 */
// 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
public class Solution19 {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode node = findFromToEnd(dummy, n + 1);
        node.next = node.next.next;
        return dummy.next;
    }

    // 查找第i个节点
    private ListNode findFromToEnd(ListNode dummy, int i) {
        ListNode p1 = dummy;
        for (int j = 0; j < i; j++) {
            p1 = p1.next;
        }
        ListNode p2 = dummy;
        while (p1 != null) {
            p1 = p1.next;
            p2 = p2.next;
        }
        return p2;
    }
}
